package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {
    /**
     * 1.上传UserInfo的相关信息,利用User的token中的id检验是否需要上传
     * 2.上传头像
     *      2.1检测该头像是否为人像
     *      2.2上传至阿里云,得到一个地址作为logo标志
     *      2.3更新数据库中logo字段(为什么这里是用更新?解释:只有先存在userinfo的相关信息,才会有logo,而想要
     *                                                              局部更新logo字段,只能使用update方法)
     *
     */

    @Autowired
    private UserService userService;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    public boolean saveUserInfo(Map<String,String> param, String token){
        User user= userService.queryUserByToken(token);
        //判断token是否存在
        if(token==null){
            return false;
        }
        //存在就创建新的userinfo
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        userInfo.setSex(param.get("gender").equals("man")? SexEnum.MAN:SexEnum.WOMAN);
        return userInfoMapper.insert(userInfo)==1;
    }

    public boolean savaUserLogo(MultipartFile file, String token) {
        User user= userService.queryUserByToken(token);
        //判断token是否存在
        if(token==null){
            return false;
        }
        //检查该头像是否为人像
        try {
            boolean flag = faceEngineService.checkIsPortrait(file.getBytes());
            //是人像,就不走if语句
            if(!flag){
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        //上传阿里云
        PicUploadResult result = this.picUploadService.upload(file);
        if (StringUtils.isEmpty(result.getName())) {
            //上传失败
            return false;
        }
        //更新logo
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());

        return this.userInfoMapper.update(userInfo, queryWrapper) == 1;
    }
}
